<?php
/**
 * Created by PhpStorm.
 * User: xuxiaoming
 * Date: 2017/11/7
 * Time: 18:50
 */


/**
 * 输出数据
 *
 * @param array $data 信息数组
 * @return string
 */
function sendJsonData(array $data)
{
    //接送数据
    header('Content-type: application/json;charset=utf-8');
    //输出json
    return json_encode(["state" => 0, "data" => dealDate($data)], JSON_UNESCAPED_UNICODE);
}

/**
 * 数据处理
 * @param $data
 * @return mixed
 */
function dealDate($data)
{
    for ($i = 0; $i < count($data); $i++) {
        if (isset($data[$i])) {
            if (is_array($data[$i])) {
                if (isset($data[$i]['created_at'])) {
                    $data[$i]['created_at'] = strtotime($data[$i]['created_at']);
                }
                if (isset($data[$i]['updated_at'])) {
                    $data[$i]['updated_at'] = strtotime($data[$i]['updated_at']);
                }
            } else {
                if (isset($data['created_at'])) {
                    $data['created_at'] = strtotime($data['created_at']);
                }
                if (isset($data['updated_at'])) {
                    $data['updated_at'] = strtotime($data['updated_at']);
                }
            }
        }
    }
    return $data;
}

/**
 * 输出信息
 *
 * @param string $message 消息
 * @param bool $error 是否为错误信息,默认为否
 * @return string
 */
function sendJsonMessage($message, $error = false)
{
    //接送数据
    header('Content-type: application/json;charset=utf-8');
    //输出json
    return json_encode(["state" => $error ? -1 : 0, "message" => $message], JSON_UNESCAPED_UNICODE);
}

/**
 * 输出信息
 *
 * @param string $message 消息
 * @param bool $error 是否为错误信息,默认为否
 * @return string
 */
function sendJsonErrorMessage($message)
{
    //接送数据
    header('Content-type: application/json;charset=utf-8');
    //输出json
    echo json_encode(["state" => -1, "message" => $message], JSON_UNESCAPED_UNICODE);
    exit();
}


function request($key = null, $default = null)
{
    if (is_null($key)) {
        return app('request');
    }

    if (is_array($key)) {
        return app('request')->only($key);
    }

    return data_get(app('request')->all(), $key, $default);
}

function validateToken()
{

    if (!request("token")) {
        sendJsonErrorMessage("令牌必须填写", true);

    }
    $token = \App\Models\Oauth::where(["access_token" => request("token")])->get()->first();
    if ($token) {
        if ($token->access_token_expire < date("Y-m-d H:i:s")) {
            sendJsonErrorMessage("令牌已经过期", true);
            exit();
        } else {
            return $token->user_id;
        }
    } else {
        sendJsonErrorMessage("令牌不存在", true);
    }

}